<?php defined('SYSPATH') or die('No direct script access.') ;
/**
 * 页面重定向地址助手
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: redirect.php 213 2012-05-24 09:33:22Z yellow.chow $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
class Helper_Redirect extends Helper
{

    /**
     * @var string
     */
    protected $_key = 'redirect';

    /**
     * 获取重定向地址 (优先从 url 获取)
     *
     * @param  string  $default
     * @return string
     */
    public function get($default = NULL)
    {
        if ($redirect = Arr::get(array_merge($_GET, $_POST), $this->_key))
        {
            $redirect = urldecode($redirect);
        }
        elseif (empty($default) OR $default == '/' OR (strpos($default, '://') === FALSE AND $default[0] != '/'))
        {
            $redirect = URL::site($default);
        }
        else
        {
            $redirect = $default;
        }

        return $this->_secured_check($redirect);
    }

    /**
     * URL 防钓鱼安全检查
     *
     * @param  string  $url
     * @return string
     * @throws Kohana_Exception
     */
    protected function _secured_check($url)
    {
        if (preg_match('#^https?://.*$#', $url) AND strpos($url, URL::scheme().'://'.URL::host()) === FALSE)
        {
            throw new Kohana_Exception('禁止使用外部地址进行安全跳转 ":url"', array(':url' => $url));
        }

        return $url;
    }

    /**
     * 创建重定向编码
     *
     * @param  string  $redirect
     * @return string
     */
    public function build($redirect = NULL)
    {
        if ($redirect == NULL)
        {
            $redirect = URL::current();
        }
        elseif ($redirect == '/' OR (strpos($redirect, '://') === FALSE AND $redirect[0] != '/'))
        {
            $redirect = URL::site($redirect);
        }


        return urlencode($this->_secured_check($redirect));
    }

    /**
     * 生成 QueryString 字符串
     *
     * @param  string  $redirect
     * @return string
     */
    public function query($redirect)
    {
        return $this->_key.'='.$this->build($redirect);
    }

    /**
     * 设定重定向地址到 URL 中
     *
     * @param  string  $url
     * @param  string  $redirect
     * @return string
     */
    public function url($url, $redirect = NULL)
    {
        $query_string = $this->query($redirect);

        if (preg_match('#'.preg_quote($this->_key).'=[\w\=]+#', $url))
        {
            return preg_replace('#'.preg_quote($this->_key).'=[\w\=]+#', $query_string, $url);
        }

        return $url.(strpos($url, '?') === FALSE ? '?' : '&').$query_string;
    }

}